<template>
  <div class="container">
    <!-- 空气质量当前状态 (不分栏) -->
    <div class="qweather-list__row">
      <div class="l-page-city-air__current">
        <div class="c-city-air-current d-flex justify-content-between align-items-center">
          <h1 class="qweather-title visible-740 sf-hidden">空气质量</h1>
          <div class="city-air__chart">
            <div class="aqi jsChartAir">
              <canvas width="140" height="140" style="width:140px;height:140px;"></canvas>
            </div>
            <h4>{{ currentAQI.level }}</h4>
          </div>
          <div class="air-charts__iaqi">
            <div class="air-charts-iaqi__row d-flex align-items-center">
              <div class="air-charts-iaqi__item">
                <div class="value text-center">{{ currentAQI.pm25 }}</div>
                <div class="progress">
                  <div class="progress__value jsChartAirPM25" :class="`air-tag--${currentAQI.category}`" :style="{ width: (currentAQI.pm25 / 250 * 100) + '%' }"></div>
                </div>
                <p class="aqi-title text-center">PM2.5</p>
              </div>
              <div class="air-charts-iaqi__item">
                <div class="value text-center">{{ currentAQI.pm10 }}</div>
                <div class="progress">
                  <div class="progress__value jsChartAirPM10" :class="`air-tag--${currentAQI.category}`" :style="{ width: (currentAQI.pm10 / 420 * 100) + '%' }"></div>
                </div>
                <p class="aqi-title text-center">PM10</p>
              </div>
              <div class="air-charts-iaqi__item">
                <div class="value text-center">{{ currentAQI.o3 }}</div>
                <div class="progress">
                  <div class="progress__value jsChartAirO3" :class="`air-tag--${currentAQI.category}`" :style="{ width: (currentAQI.o3 / 800 * 100) + '%' }"></div>
                </div>
                <p class="aqi-title text-center">O<sub>3</sub></p>
              </div>
            </div>
            <div class="air-charts-iaqi__row d-flex align-items-center">
              <div class="air-charts-iaqi__item">
                <div class="value text-center">{{ currentAQI.co }}</div>
                <div class="progress">
                  <div class="progress__value jsChartAirCo" :class="`air-tag--${currentAQI.category}`" :style="{ width: (currentAQI.co / 90 * 100) + '%' }"></div>
                </div>
                <p class="aqi-title text-center">CO</p>
              </div>
              <div class="air-charts-iaqi__item">
                <div class="value text-center">{{ currentAQI.no2 }}</div>
                <div class="progress">
                  <div class="progress__value jsChartAirNo2" :class="`air-tag--${currentAQI.category}`" :style="{ width: (currentAQI.no2 / 280 * 100) + '%' }"></div>
                </div>
                <p class="aqi-title text-center">NO<sub>2</sub></p>
              </div>
              <div class="air-charts-iaqi__item">
                <div class="value text-center">{{ currentAQI.so2 }}</div>
                <div class="progress">
                  <div class="progress__value jsChartAirSo2" :class="`air-tag--${currentAQI.category}`" :style="{ width: (currentAQI.so2 / 500 * 100) + '%' }"></div>
                </div>
                <p class="aqi-title text-center">SO<sub>2</sub></p>
              </div>
            </div>
          </div>
          <div class="city-air__txt advise">
            <p class="hidden-740">
              {{ healthAdvice.description }}
            </p>
            <h5 class="visible-740">小建议</h5>
            <p>
              {{ healthAdvice.suggestion }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 其他内容左右两栏布局 -->
    <div class="qweather-layout d-flex align-items-start justify-content-between" style="height:auto!important">
      <!-- 左侧列表 -->
      <div class="qweather-list" style="height:auto!important">
            
            <!-- 空气质量预报 -->
            <div class="qweather-list__row">
              <div class="l-page-city-air__forecast">
                <div class="c-city-air-forecast">
                  <h3 class="city-air-forecast__title text-center">空气质量预报</h3>
                  <div class="city-air-forecast__list">
                    <div v-for="(forecast, index) in airForecasts" :key="index" class="air-forecast-item d-flex align-items-center justify-content-between">
                      <div class="forecast-date">
                        <div class="date-week">{{ forecast.week }}</div>
                        <div class="date-info">{{ forecast.date }}</div>
                      </div>
                      <div class="forecast-bar">
                        <div class="bar-container">
                          <div class="bar-fill" :class="forecast.levelClass" :style="{ width: forecast.percentage + '%' }"></div>
                        </div>
                      </div>
                      <div class="forecast-value text-center">
                        <div class="aqi-value">{{ forecast.value }}</div>
                        <div class="aqi-level">{{ forecast.level }}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 空气质量排行 -->
            <div class="qweather-list__row">
              <div class="l-page-city-air__rank">
                <div class="c-city-air-rank">
                  <h3 class="city-air-rank__title text-center">{{ currentLocation.district }}空气质量排行</h3>
                  <div class="city-air-rank__list">
                    <div v-for="(rank, index) in airRankings" :key="index" 
                         :class="['rank-item d-flex align-items-center justify-content-between', { 'active': rank.active }]">
                      <div class="rank-info d-flex align-items-center">
                        <span class="rank-num">{{ rank.num }}</span>
                        <span class="rank-location">{{ rank.location }}</span>
                      </div>
                      <span class="rank-value" :class="rank.levelClass">{{ rank.level }} {{ rank.value }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 月度空气质量和蓝天数图表 -->
            <div class="qweather-list__row">
              <div class="l-page-city-air__monthly">
                <div class="c-city-air-monthly">
                  <h3 class="qweather-title">月度空气质量和蓝天数</h3>
                  <div class="monthly-chart" ref="monthlyChart"></div>
                </div>
              </div>
            </div>
            
            <!-- 12个月空气质量分布 -->
            <div class="qweather-list__row">
              <div class="c-city-air-12month">
                <h3 class="qweather-title">{{ currentLocation.district }}最近12个月空气质量分布</h3>
                <div class="air-12month-calendar">
                  <div class="calendar-wrapper">
                    <div class="month-labels-column">
                      <div v-for="month in monthlyAirData" :key="month.yearMonth" class="month-label">
                        {{ month.yearMonth }}
                      </div>
                    </div>
                    <div class="days-scroll-container">
                      <div class="days-grid-wrapper">
                        <div v-for="month in monthlyAirData" :key="month.yearMonth" class="month-row">
                          <div v-for="day in month.days" :key="day.date"
                               :class="['day-cell', getAQIColorClass(day.aqi)]"
                               :title="`${day.date}: AQI ${day.aqi} ${getAQILevel(day.aqi)}`">
                            {{ day.aqi }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="air-legend">
                  <div class="legend-item">
                    <span class="legend-dot legend-excellent"></span>
                    <span class="legend-text">优</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-dot legend-good"></span>
                    <span class="legend-text">良</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-dot legend-light"></span>
                    <span class="legend-text">轻度</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-dot legend-moderate"></span>
                    <span class="legend-text">中度</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-dot legend-heavy"></span>
                    <span class="legend-text">重度</span>
                  </div>
                  <div class="legend-item">
                    <span class="legend-dot legend-severe"></span>
                    <span class="legend-text">严重</span>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 数据来源 -->
            <div class="qweather-list__row">
              <div class="l-page-city-air__source">
                <div class="c-data-source">
                  <a href="http://www.cnemc.cn/" class="data-source__txt">空气质量来源：中国环境监测总站</a>
                  <p><i>*</i>表示首要污染物</p>
                </div>
              </div>
            </div>
      </div>

      <!-- 右侧菜单 -->
      <div class="qweather-menu" style="height:auto!important">
        <!-- 占位内容 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

// 空气质量预报数据
const airForecasts = ref([
  { week: '今天', date: '09月15日', value: 79, level: '良', percentage: 30, levelClass: 'air-tag--2' },
  { week: '周二', date: '09月16日', value: 87, level: '良', percentage: 35, levelClass: 'air-tag--2' },
  { week: '周三', date: '09月17日', value: 72, level: '良', percentage: 28, levelClass: 'air-tag--2' },
  { week: '周四', date: '09月18日', value: 64, level: '良', percentage: 25, levelClass: 'air-tag--2' },
  { week: '周五', date: '09月19日', value: 69, level: '良', percentage: 27, levelClass: 'air-tag--2' },
  { week: '周六', date: '09月20日', value: 82, level: '良', percentage: 32, levelClass: 'air-tag--2' },
  { week: '周日', date: '09月21日', value: 44, level: '优', percentage: 17, levelClass: 'air-tag--1' }
])

// 空气质量排行数据
const airRankings = ref([
  { num: '1', location: '儋州市，海南省', level: '优', value: '10', levelClass: 'rank-tag--1' },
  { num: '2', location: '楚雄彝族自治州，云南省', level: '优', value: '10', levelClass: 'rank-tag--1' },
  { num: '3', location: '楚雄市，云南省', level: '优', value: '10', levelClass: 'rank-tag--1' },
  { num: '4', location: '白沙黎族自治县，海南省', level: '优', value: '11', levelClass: 'rank-tag--1' },
  { num: '5', location: '双柏县，云南省', level: '优', value: '11', levelClass: 'rank-tag--1' },
  { num: '6', location: '景东彝族自治县，云南省', level: '优', value: '11', levelClass: 'rank-tag--1' },
  { num: '7', location: '巴林右旗，内蒙古自治区', level: '优', value: '12', levelClass: 'rank-tag--1' },
  { num: '8', location: '东方市，海南省', level: '优', value: '12', levelClass: 'rank-tag--1' },
  { num: '9', location: '昌江黎族自治县，海南省', level: '优', value: '12', levelClass: 'rank-tag--1' },
  { num: '0', location: '洪山区，湖北省', level: '优', value: '37', levelClass: 'rank-tag--1', active: true }
])

// 月度空气质量和蓝天数数据
const monthlyChart = ref(null)
const monthlyData = ref({
  months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  averageAQI: [68, 72, 85, 78, 82, 75, 69, 71, 77, 73, 66, 70],
  blueSkyDays: [18, 15, 12, 16, 14, 17, 20, 19, 16, 18, 22, 19]
})

// 12个月空气质量数据
const monthlyAirData = ref([])

// 健康建议
const healthAdvice = ref({
  description: '空气质量可接受',
  suggestion: '一般人群可正常户外活动'
})

// 根据AQI等级获取健康建议
const getHealthAdvice = (aqi) => {
  if (aqi <= 50) {
    return {
      description: '空气质量令人满意，基本无空气污染',
      suggestion: '各类人群可正常活动'
    }
  } else if (aqi <= 100) {
    return {
      description: '空气质量可接受，但某些污染物可能对极少数异常敏感人群健康有较弱影响',
      suggestion: '极少数异常敏感人群应减少户外活动'
    }
  } else if (aqi <= 150) {
    return {
      description: '易感人群症状有轻度加剧，健康人群出现刺激症状',
      suggestion: '儿童、老年人及心脏病、呼吸系统疾病患者应减少长时间、高强度的户外锻炼'
    }
  } else if (aqi <= 200) {
    return {
      description: '进一步加剧易感人群症状，可能对健康人群心脏、呼吸系统有影响',
      suggestion: '儿童、老年人及心脏病、呼吸系统疾病患者避免长时间、高强度的户外锻炼，一般人群适量减少户外运动'
    }
  } else if (aqi <= 300) {
    return {
      description: '心脏病和肺病患者症状显著加剧，运动耐受力降低',
      suggestion: '儿童、老年人及心脏病、呼吸系统疾病患者应停留在室内，停止户外运动，一般人群减少户外运动'
    }
  } else {
    return {
      description: '健康人群运动耐受力降低，有明显强烈症状',
      suggestion: '儿童、老年人和病人应停留在室内，避免体力消耗，一般人群避免户外活动'
    }
  }
}

// API配置
const API_KEY = '78db6a9c3b4d445881d8fa1ba2d0fa8a'
const API_BASE_URL = 'https://pr6yvxwd8j.re.qweatherapi.com'

// 当前位置
const currentLocation = ref({
  longitude: 114.40,
  latitude: 30.50,
  city: '武汉市',
  district: '洪山区'
})

// 当前空气质量数据
const currentAQI = ref({
  aqi: 37,
  level: '优',
  category: 1,
  pm25: 13,
  pm10: 20,
  o3: 116,
  co: 0.7,
  no2: 16,
  so2: 4
})

// 获取AQI等级信息
const getAQILevel = (aqi) => {
  if (aqi <= 50) return { level: '优', category: 1, color: '#00e400' }
  if (aqi <= 100) return { level: '良', category: 2, color: '#ffff00' }
  if (aqi <= 150) return { level: '轻度污染', category: 3, color: '#ff7e00' }
  if (aqi <= 200) return { level: '中度污染', category: 4, color: '#ff0000' }
  if (aqi <= 300) return { level: '重度污染', category: 5, color: '#8f3f97' }
  return { level: '严重污染', category: 6, color: '#7e0023' }
}

// 获取当前位置
const getCurrentLocation = () => {
  return new Promise((resolve, reject) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        async (position) => {
          currentLocation.value.latitude = position.coords.latitude
          currentLocation.value.longitude = position.coords.longitude

          // 获取城市信息
          await getCityInfo(position.coords.longitude, position.coords.latitude)
          resolve()
        },
        (error) => {
          console.error('获取位置失败:', error)
          // 使用默认位置
          resolve()
        },
        {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 0
        }
      )
    } else {
      console.log('浏览器不支持地理定位')
      resolve()
    }
  })
}

// 获取城市信息
const getCityInfo = async (longitude, latitude) => {
  try {
    const response = await axios.get(
      `${API_BASE_URL}/geo/v2/city/lookup`,
      {
        params: {
          location: `${longitude},${latitude}`,
          key: API_KEY
        }
      }
    )

    if (response.data && response.data.code === '200' && response.data.location) {
      const location = response.data.location[0]
      currentLocation.value.city = location.adm2 || location.name
      currentLocation.value.district = location.name
    }
  } catch (error) {
    console.error('获取城市信息失败:', error)
  }
}

// 获取空气质量数据
const fetchAirQuality = async () => {
  try {
    const location = `${currentLocation.value.longitude.toFixed(2)},${currentLocation.value.latitude.toFixed(2)}` // 经度,纬度格式

    const response = await axios.get(
      `${API_BASE_URL}/v7/air/now`,
      {
        params: {
          location: location,
          key: API_KEY,
          lang: 'zh'
        }
      }
    )

    if (response.data && response.data.code === '200' && response.data.now) {
      const data = response.data.now

      // 更新当前AQI数据
      currentAQI.value.aqi = parseInt(data.aqi)
      const levelInfo = getAQILevel(parseInt(data.aqi))
      currentAQI.value.level = data.category || levelInfo.level
      currentAQI.value.category = parseInt(data.level) || levelInfo.category

      // 更新污染物数据
      currentAQI.value.pm25 = parseInt(data.pm2p5) || currentAQI.value.pm25
      currentAQI.value.pm10 = parseInt(data.pm10) || currentAQI.value.pm10
      currentAQI.value.o3 = parseInt(data.o3) || currentAQI.value.o3
      currentAQI.value.co = parseFloat(data.co) || currentAQI.value.co
      currentAQI.value.no2 = parseInt(data.no2) || currentAQI.value.no2
      currentAQI.value.so2 = parseInt(data.so2) || currentAQI.value.so2

      // 更新健康建议
      healthAdvice.value = getHealthAdvice(currentAQI.value.aqi)

      // 更新预报数据
      await fetchAirForecast(location)
    }
  } catch (error) {
    console.error('获取空气质量数据失败:', error)
    // 使用默认数据
  }
}

// 获取空气质量预报数据
const fetchAirForecast = async (location) => {
  try {
    const response = await axios.get(
      `${API_BASE_URL}/v7/air/5d`,
      {
        params: {
          location: location,
          key: API_KEY,
          lang: 'zh'
        }
      }
    )

    if (response.data && response.data.code === '200' && response.data.daily) {
      const dailyData = response.data.daily
      const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      const today = new Date()

      // 如果API返回的数据少于7天，用模拟数据补齐
      const forecastData = []

      // 先处理API返回的真实数据
      for (let i = 0; i < Math.min(dailyData.length, 7); i++) {
        const day = dailyData[i]
        const date = new Date(day.fxDate)
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const dayOfMonth = date.getDate().toString().padStart(2, '0')

        let weekDay
        if (i === 0) {
          weekDay = '今天'
        } else if (i === 1) {
          weekDay = '明天'
        } else {
          weekDay = weekDays[date.getDay()]
        }

        const aqi = parseInt(day.aqi)
        const levelInfo = getAQILevel(aqi)

        forecastData.push({
          week: weekDay,
          date: `${month}月${dayOfMonth}日`,
          value: aqi,
          level: day.category || levelInfo.level,
          percentage: Math.min(100, (aqi / 300) * 100),
          levelClass: `air-tag--${parseInt(day.level) || levelInfo.category}`
        })
      }

      // 如果不足7天，用模拟数据补齐
      if (forecastData.length < 7) {
        const lastAQI = forecastData.length > 0 ? forecastData[forecastData.length - 1].value : currentAQI.value.aqi

        for (let i = forecastData.length; i < 7; i++) {
          const date = new Date(today)
          date.setDate(today.getDate() + i)

          const month = (date.getMonth() + 1).toString().padStart(2, '0')
          const dayOfMonth = date.getDate().toString().padStart(2, '0')
          const weekDay = i === 0 ? '今天' : (i === 1 ? '明天' : weekDays[date.getDay()])

          // 基于前一天的AQI生成模拟数据
          const variation = Math.floor(Math.random() * 20) - 10
          const forecastAQI = Math.max(10, Math.min(300, lastAQI + variation))
          const levelInfo = getAQILevel(forecastAQI)

          forecastData.push({
            week: weekDay,
            date: `${month}月${dayOfMonth}日`,
            value: forecastAQI,
            level: levelInfo.level,
            percentage: Math.min(100, (forecastAQI / 300) * 100),
            levelClass: `air-tag--${levelInfo.category}`
          })
        }
      }

      airForecasts.value = forecastData
    } else {
      // 如果预报数据获取失败，使用模拟数据
      updateForecastData()
    }
  } catch (error) {
    console.error('获取空气质量预报失败:', error)
    // 使用模拟数据
    updateForecastData()
  }
}

// 更新预报数据（基于当前AQI生成模拟预报）
const updateForecastData = () => {
  const baseAQI = currentAQI.value.aqi
  const dates = ['今天', '周二', '周三', '周四', '周五', '周六', '周日']
  const dateInfos = ['09月15日', '09月16日', '09月17日', '09月18日', '09月19日', '09月20日', '09月21日']

  airForecasts.value = dates.map((week, index) => {
    // 生成基于当前AQI的随机预报值
    const variation = Math.floor(Math.random() * 40) - 20
    const forecastAQI = Math.max(10, Math.min(300, baseAQI + variation))
    const levelInfo = getAQILevel(forecastAQI)

    return {
      week,
      date: dateInfos[index],
      value: forecastAQI,
      level: levelInfo.level,
      percentage: Math.min(100, (forecastAQI / 300) * 100),
      levelClass: `air-tag--${levelInfo.category}`
    }
  })
}

// 绘制AQI圆形图表
const drawAQIChart = () => {
  const canvas = document.querySelector('.aqi canvas')
  if (canvas) {
    const ctx = canvas.getContext('2d')
    const centerX = canvas.width / 2
    const centerY = canvas.height / 2
    const radius = 60
    
    // 绘制圆形彩虹渐变背景
    const gradient = ctx.createConicGradient(Math.PI * 1.5, centerX, centerY)
    gradient.addColorStop(0, '#00e400')
    gradient.addColorStop(0.167, '#ffff00')
    gradient.addColorStop(0.333, '#ff7e00')
    gradient.addColorStop(0.5, '#ff0000')
    gradient.addColorStop(0.667, '#8f3f97')
    gradient.addColorStop(0.833, '#7e0023')
    gradient.addColorStop(1, '#00e400')
    
    ctx.beginPath()
    ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI)
    ctx.fillStyle = gradient
    ctx.fill()
    
    // 绘制中心白色圆形
    ctx.beginPath()
    ctx.arc(centerX, centerY, radius - 15, 0, 2 * Math.PI)
    ctx.fillStyle = 'white'
    ctx.fill()
    
    // 绘制AQI数值
    ctx.font = 'bold 36px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto'
    const levelInfo = getAQILevel(currentAQI.value.aqi)
    ctx.fillStyle = levelInfo.color
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(currentAQI.value.aqi.toString(), centerX, centerY)
  }
}

// 初始化月度空气质量和蓝天数图表
const initMonthlyChart = () => {
  if (!monthlyChart.value) return
  
  const myChart = echarts.init(monthlyChart.value)
  
  const option = {
    title: {
      text: '2025年空气质量和蓝天数统计',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['平均AQI', '蓝天数'],
      top: 40,
      left: 'center',
      itemGap: 30,
      textStyle: {
        fontSize: 13,
        color: '#666'
      }
    },
    xAxis: [
      {
        type: 'category',
        data: monthlyData.value.months,
        axisPointer: {
          type: 'shadow'
        },
        axisLine: {
          lineStyle: {
            color: '#E5E5E5'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          fontSize: 12,
          color: '#666'
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: 'AQI',
        min: 0,
        max: 120,
        position: 'left',
        nameTextStyle: {
          fontSize: 12,
          color: '#666'
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          fontSize: 12,
          color: '#666'
        },
        splitLine: {
          lineStyle: {
            color: '#F0F0F0',
            type: 'dashed'
          }
        }
      },
      {
        type: 'value',
        name: '蓝天数(天)',
        min: 0,
        max: 31,
        position: 'right',
        nameTextStyle: {
          fontSize: 12,
          color: '#666'
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          fontSize: 12,
          color: '#666'
        },
        splitLine: {
          show: false
        }
      }
    ],
    grid: {
      left: '8%',
      right: '8%',
      top: '25%',
      bottom: '15%',
      containLabel: true
    },
    series: [
      {
        name: '平均AQI',
        type: 'bar',
        yAxisIndex: 0,
        data: monthlyData.value.averageAQI,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#FFB84D' },
            { offset: 1, color: '#FF8C42' }
          ]),
          borderRadius: [4, 4, 0, 0]
        },
        barWidth: '40%'
      },
      {
        name: '蓝天数',
        type: 'line',
        yAxisIndex: 1,
        data: monthlyData.value.blueSkyDays,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          color: '#4A9FFF',
          width: 3
        },
        itemStyle: {
          color: '#4A9FFF',
          borderColor: '#fff',
          borderWidth: 2
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(74, 159, 255, 0.3)' },
            { offset: 1, color: 'rgba(74, 159, 255, 0.05)' }
          ])
        }
      }
    ]
  }
  
  myChart.setOption(option)
  
  // 响应式处理
  const resizeChart = () => {
    myChart.resize()
  }
  
  window.addEventListener('resize', resizeChart)
}

// 生成历史空气质量数据
const generateHistoricalData = () => {
  const today = new Date()
  const dates = []
  const thisYearAQI = []
  const lastYearAQI = []
  
  // 生成最近30天的历史数据
  for (let i = 29; i >= 0; i--) {
    const date = new Date(today)
    date.setDate(today.getDate() - i)
    
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    dates.push(`${month}/${day}`)
    
    // 生成今年模拟AQI数据 (基于当前AQI波动)
    const baseAQI = currentAQI.value.aqi
    const variation = Math.floor(Math.random() * 40) - 20
    const todayAQI = Math.max(10, Math.min(300, baseAQI + variation))
    thisYearAQI.push(todayAQI)
    
    // 生成去年同期模拟数据 (通常略有不同)
    const lastYearVariation = Math.floor(Math.random() * 50) - 25
    const lastYearValue = Math.max(10, Math.min(300, baseAQI + lastYearVariation))
    lastYearAQI.push(lastYearValue)
  }
  
  historicalData.value = {
    dates,
    thisYearAQI,
    lastYearAQI
  }
}

// 初始化历史空气质量图表
const initHistoricalChart = () => {
  if (!historicalChart.value) return
  
  const myChart = echarts.init(historicalChart.value)
  
  const option = {
    title: {
      text: '最近30天空气质量对比',
      left: 'center',
      top: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let result = params[0].name + '<br/>'
        params.forEach(param => {
          result += param.marker + param.seriesName + ': AQI ' + param.value + '<br/>'
        })
        return result
      }
    },
    legend: {
      data: ['今年', '去年同期'],
      top: 40,
      left: 'center',
      itemGap: 30,
      textStyle: {
        fontSize: 13,
        color: '#666'
      }
    },
    grid: {
      left: '8%',
      right: '8%',
      top: '25%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: historicalData.value.dates,
      axisLine: {
        lineStyle: {
          color: '#E5E5E5'
        }
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        fontSize: 12,
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      name: 'AQI',
      nameTextStyle: {
        fontSize: 12,
        color: '#666'
      },
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        fontSize: 12,
        color: '#666'
      },
      splitLine: {
        lineStyle: {
          color: '#F0F0F0',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '今年',
        type: 'line',
        data: historicalData.value.thisYearAQI,
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          color: '#4A9FFF',
          width: 3
        },
        itemStyle: {
          color: '#4A9FFF'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(74, 159, 255, 0.3)' },
            { offset: 1, color: 'rgba(74, 159, 255, 0.05)' }
          ])
        }
      },
      {
        name: '去年同期',
        type: 'line',
        data: historicalData.value.lastYearAQI,
        smooth: true,
        symbol: 'diamond',
        symbolSize: 5,
        lineStyle: {
          color: '#FFB84D',
          width: 2,
          type: 'dashed'
        },
        itemStyle: {
          color: '#FFB84D'
        }
      }
    ]
  }
  
  myChart.setOption(option)
  
  // 响应式处理
  const resizeChart = () => {
    myChart.resize()
  }
  
  window.addEventListener('resize', resizeChart)
}

// 生成12个月空气质量数据
const generate12MonthAirData = () => {
  const currentDate = new Date()
  const months = []
  
  // 生成最近12个月的数据
  for (let i = 11; i >= 0; i--) {
    const monthDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - i, 1)
    const year = monthDate.getFullYear()
    const month = monthDate.getMonth() + 1
    const yearMonth = `${year}/${String(month).padStart(2, '0')}`
    
    // 获取该月的天数
    const daysInMonth = new Date(year, month, 0).getDate()
    const days = []
    
    // 为每天生成模拟AQI数据
    for (let day = 1; day <= daysInMonth; day++) {
      // 基于季节生成不同的AQI基础值
      let baseAQI = 50
      if (month >= 11 || month <= 2) { // 冬季，污染较重
        baseAQI = 80
      } else if (month >= 6 && month <= 8) { // 夏季，相对较好
        baseAQI = 45
      } else if (month >= 3 && month <= 5) { // 春季
        baseAQI = 65
      } else { // 秋季
        baseAQI = 55
      }
      
      // 添加随机波动
      const variation = Math.floor(Math.random() * 60) - 30
      const aqi = Math.max(10, Math.min(300, baseAQI + variation))
      
      days.push({
        date: `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`,
        aqi: aqi
      })
    }
    
    months.push({
      yearMonth,
      days
    })
  }
  
  monthlyAirData.value = months
}

// 根据AQI值获取颜色类
const getAQIColorClass = (aqi) => {
  if (aqi <= 50) return 'aqi-excellent'
  if (aqi <= 100) return 'aqi-good'
  if (aqi <= 150) return 'aqi-light'
  if (aqi <= 200) return 'aqi-moderate'
  if (aqi <= 300) return 'aqi-heavy'
  return 'aqi-severe'
}

// 在组件挂载后获取数据并绘制图表
onMounted(async () => {
  // 先获取当前位置
  await getCurrentLocation()
  // 然后获取空气质量数据
  await fetchAirQuality()
  // 绘制图表
  drawAQIChart()
  
  // 生成12个月空气质量数据
  generate12MonthAirData()
  
  // 初始化图表
  nextTick(() => {
    initMonthlyChart()
  })
})
</script>

<style scoped>
/* 容器样式 */
.container {
  max-width: 1200px;
  padding-left: 20px;
  padding-right: 20px;
  margin: 0 auto;
}

/* 左右布局 */
.qweather-layout {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.qweather-list {
  flex: 1 0 auto;
  width: 0;
}

.qweather-list .qweather-list__row {
  margin: 0 0 20px;
  background: none;
  border: none;
  padding: 0;
}

.qweather-list .qweather-list__row:last-child {
  margin: 0;
}

/* 顶部空气质量当前状态部分 */
.container > .qweather-list__row:first-child {
  margin: 20px 0;
  background: none;
  border: none;
  padding: 0;
}

.qweather-menu {
  flex: 0 0 300px;
  width: 0;
  max-width: 300px;
  margin-left: 20px;
}

.justify-content-between {
  justify-content: space-between !important;
}

.qweather-title {
  font-size: 20px;
  font-weight: 500;
  line-height: 22px;
  color: #333;
  text-align: center;
}

/* 空气质量当前状态 */
.l-page-city-air__current {
  width: 100%;
}

.c-city-air-current {
  background: #fff;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

/* AQI圆形图表 */
.city-air__chart {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 40px;
}

.city-air__chart h4 {
  margin: 10px 0 0 0;
  font-size: 20px;
  font-weight: normal;
  color: #333;
}

.aqi {
  position: relative;
  width: 140px;
  height: 140px;
}

/* 空气质量指标 */
.air-charts__iaqi {
  flex: 1;
}

.air-charts-iaqi__row {
  gap: 30px;
}

.air-charts-iaqi__row:not(:last-child) {
  margin-bottom: 20px;
}

.air-charts-iaqi__item {
  text-align: left;
  min-width: 100px;
}

.value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.progress {
  width: 100%;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  margin-bottom: 4px;
  overflow: hidden;
}

.progress__value {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.air-tag--1 {
  background: #95B359;
}

.air-tag--2 {
  background: #A9A538;
}

.air-tag--3 {
  background: #ff7e00;
}

.air-tag--4 {
  background: #ff0000;
}

.air-tag--5 {
  background: #8f3f97;
}

.air-tag--6 {
  background: #7e0023;
}

.aqi-title {
  font-size: 12px;
  color: #666;
  margin: 0;
}

/* 空气质量预报 */
.l-page-city-air__forecast {
  width: 100%;
}

.c-city-air-forecast {
  background: #fff;
  border-radius: 16px;
  padding: 30px 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.city-air-forecast__title {
  font-size: 20px;
  font-weight: 500;
  color: #333;
  margin: 0 0 20px 0;
}

.city-air-forecast__list {
  max-width: 600px;
  margin: 0 auto;
}

.air-forecast-item {
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.air-forecast-item:last-child {
  border-bottom: none;
}

.forecast-date {
  flex: 0 0 100px;
}

.date-week {
  font-size: 14px;
  color: #333;
  margin-bottom: 2px;
}

.date-info {
  font-size: 12px;
  color: #999;
}

.forecast-bar {
  flex: 1;
  padding: 0 20px;
}

.bar-container {
  width: 100%;
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.bar-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.forecast-value {
  flex: 0 0 80px;
}

.forecast-value .aqi-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 2px;
}

.forecast-value .aqi-level {
  font-size: 14px;
  color: #666;
}

/* 空气质量排行 */
.l-page-city-air__rank {
  width: 100%;
}

.c-city-air-rank {
  background: #fff;
  border-radius: 16px;
  padding: 30px 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.city-air-rank__title {
  font-size: 20px;
  font-weight: 500;
  color: #333;
  margin: 0 0 20px 0;
}

.city-air-rank__list {
  max-width: 600px;
  margin: 0 auto;
}

.rank-item {
  padding: 12px 16px;
  margin-bottom: 8px;
  background: #f8f8f8;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.rank-item:last-child {
  margin-bottom: 0;
}

.rank-item.active {
  background: #e6f4ff;
  border: 1px solid #427BFF;
}

.rank-info {
  gap: 12px;
}

.rank-num {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: #ddd;
  color: #666;
  border-radius: 50%;
  font-size: 14px;
  font-weight: bold;
}

.rank-item.active .rank-num {
  background: #427BFF;
  color: #fff;
}

.rank-location {
  font-size: 14px;
  color: #333;
}

.rank-value {
  font-size: 14px;
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 14px;
  white-space: nowrap;
}

.rank-tag--1 {
  background: #95B359;
  color: #fff;
}

.rank-tag--2 {
  background: #A9A538;
  color: #fff;
}

/* 月度空气质量和蓝天数图表 */
.l-page-city-air__monthly {
  width: 100%;
}

.c-city-air-monthly {
  background: #fff;
  border-radius: 16px;
  padding: 30px 20px 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  border: 1px solid #e5eaef;
}

.monthly-chart {
  width: 100%;
  height: 400px;
  margin-top: 20px;
}

/* 12个月空气质量分布 */
.c-city-air-12month {
  border-radius: 16px;
  background: #fff;
  border: 1px solid #e5eaef;
  padding: 30px 20px 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.air-12month-calendar {
  margin-top: 25px;
}

.calendar-wrapper {
  display: flex;
  align-items: flex-start;
}

.month-labels-column {
  width: 95px;
  flex-shrink: 0;
}

.month-label {
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: #666;
  font-size: 14px;
  font-weight: 500;
  padding-right: 15px;
}

.days-scroll-container {
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: thin;
  scrollbar-color: #ccc #f5f5f5;
}

.days-scroll-container::-webkit-scrollbar {
  height: 6px;
}

.days-scroll-container::-webkit-scrollbar-track {
  background: #f5f5f5;
  border-radius: 3px;
}

.days-scroll-container::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.days-scroll-container::-webkit-scrollbar-thumb:hover {
  background: #999;
}

.days-grid-wrapper {
  display: inline-block;
  min-width: fit-content;
}

.month-row {
  display: flex;
  gap: 2px;
  height: 30px;
  align-items: center;
}

.day-cell {
  width: 36px;
  height: 22px;
  min-width: 36px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  font-weight: 500;
  font-family: 'Consolas', 'Monaco', 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New', monospace;
  color: #fff;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.day-cell:hover {
  transform: scale(1.1);
  z-index: 1;
  position: relative;
  box-shadow: 0 2px 8px rgba(0,0,0,0.2);
}

/* AQI 等级颜色 */
.aqi-excellent {
  background-color: #95B359; /* 优 - 绿色 */
}

.aqi-good {
  background-color: #A9A538; /* 良 - 黄绿色 */
}

.aqi-light {
  background-color: #F5A623; /* 轻度污染 - 橙色 */
}

.aqi-moderate {
  background-color: #F56C6C; /* 中度污染 - 红色 */
}

.aqi-heavy {
  background-color: #8E4EC6; /* 重度污染 - 紫色 */
}

.aqi-severe {
  background-color: #8B0000; /* 严重污染 - 深红色 */
}

.air-legend {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.air-legend .legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-excellent {
  background-color: #95B359;
}

.legend-good {
  background-color: #A9A538;
}

.legend-light {
  background-color: #F5A623;
}

.legend-moderate {
  background-color: #F56C6C;
}

.legend-heavy {
  background-color: #8E4EC6;
}

.legend-severe {
  background-color: #8B0000;
}

.air-legend .legend-text {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

/* 数据来源 */
.l-page-city-air__source {
  margin-top: 20px;
  width: 100%;
}

.c-data-source {
  padding: 20px;
  background: #f8f8f8;
  border-radius: 8px;
}

.data-source__txt {
  color: #666;
  text-decoration: none;
  font-size: 14px;
  display: inline-block;
  margin-bottom: 8px;
}

.data-source__txt:hover {
  color: #427BFF;
  text-decoration: underline;
}

.c-data-source p {
  margin: 0;
  font-size: 12px;
  color: #999;
}

.c-data-source i {
  font-style: normal;
  color: #ff7e00;
  font-weight: bold;
}

/* 空气质量文字区域 */
.city-air__txt {
  flex: 1;
  margin: 0 20px;
  max-width: 300px;
}

.city-air__txt.advise {
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  margin-left: 40px;
  margin-right: 0;
}

.city-air__txt.advise p {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin: 8px 0;
}

.city-air__txt.advise h5 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 12px 0 8px 0;
}

.hidden-740 {
  display: block;
}

.visible-740 {
  display: block;
}

/* 工具类 */
.text-center {
  text-align: center;
}

.d-flex {
  display: flex;
}

.align-items-center {
  align-items: center;
}

.justify-content-between {
  justify-content: space-between;
}

.visible-740 {
  display: none;
}

.sf-hidden {
  display: none;
}

@media (max-width: 740px) {
  .visible-740 {
    display: block;
  }
  
  .c-city-air-current {
    flex-direction: column;
    gap: 20px;
  }
  
  .air-charts-iaqi__row {
    justify-content: center;
  }
  
  .air-charts-iaqi__item {
    min-width: 60px;
  }
}

/* 响应式设计 */
@media (max-width: 739px) {
  .container {
    padding-left: 16px;
    padding-right: 16px;
  }
  
  .qweather-layout {
    flex-direction: column !important;
    justify-content: center !important;
    align-items: stretch !important;
  }
  
  .qweather-layout .qweather-list {
    flex: 1 0 100%;
    width: 100%;
    max-width: 100%;
  }
  
  .qweather-layout .qweather-list .qweather-list__row {
    margin: 0 0 12px;
  }
  
  .qweather-layout .qweather-menu {
    flex: 1 0 100%;
    width: 100%;
    max-width: 100%;
    margin: 12px 0 0;
  }
  
  .c-city-air-current {
    padding: 20px;
  }
  
  .c-city-air-12month {
    padding: 20px 15px;
  }
  
  .month-label {
    width: 60px;
    font-size: 12px;
    margin-right: 10px;
  }
  
  .day-cell {
    width: 28px;
    height: 20px;
    font-size: 10px;
  }
  
  .air-legend {
    flex-wrap: wrap;
    gap: 15px;
  }
  
  .air-legend .legend-text {
    font-size: 11px;
  }
}
</style>